/*
 * Created by: Peter Weissbrod
 * Created: Monday, January 21, 2008
 */
using System;
using PostSharp.Laos;
using PostSharp.UserSamples.Exceptions;
using PostSharp.UserSamples.Utils;

namespace PostSharp.UserSamples.Validators
{
    /// <summary>
    /// Validates the min and max length of strings
    /// </summary>
    [Serializable]
    public class StringLengthValidator : OnMethodBoundaryAspect
    {
        /// <summary>
        /// The min length of the property
        /// </summary>
        public int MinLength
        {
            get;
            set;
        }
        /// <summary>
        /// The max length of the property
        /// </summary>
        public int MaxLength
        {
            get;
            set;
        }
        /// <summary>
        /// Public setter properties only
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        public override bool CompileTimeValidate(System.Reflection.MethodBase method)
        {
            return CompileTimeValidateScenario.ValidateForPublicPropertySetter(method) &&
                   CompileTimeValidateScenario.RestrictPropertySetterToSpecificType(method, typeof(string));
        }
        /// <summary>
        /// Throw an exception if the string length is out of the defined boundaries
        /// </summary>
        /// <param name="eventArgs"></param>
        public override void OnEntry(MethodExecutionEventArgs eventArgs)
        {
            if (eventArgs.GetArguments() == null)
                return;
            string value = (string) eventArgs.GetArguments()[0];
            if (value.Length < MinLength)
                throw new ValidationException(
                    "Value [" + value + "] was shorter than the minimum allowed length of [" + MinLength + "]",
                    eventArgs);
            if (value.Length > MaxLength)
                throw new ValidationException(
                    "Value [" + value + "] was longer than the maximum allowed length of [" + MaxLength + "]", eventArgs);
            base.OnEntry(eventArgs);
        }
    }
}